package com.inspinia.upms.server.controller.upms;

import com.inspinia.auth.rpc.api.AuthService;
import com.inspinia.base.common.model.AjaxResult;
import com.inspinia.base.common.model.Status;
import com.inspinia.base.util.StringUtils;
import com.inspinia.upms.common.model.resource.UpmsResourcesType;
import com.inspinia.upms.common.model.resource.UpmsResource;
import com.inspinia.upms.rpc.api.UpmsResourceService;
import com.inspinia.upms.rpc.api.UpmsUserService;
import com.inspinia.upms.server.controller.BaseController;
import org.reflections.Reflections;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.beans.PropertyEditorSupport;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * Created by Veblen on 2017/1/1.
 */
@Controller
@RequestMapping("upms/resource/")
public class UpmsResourceController extends BaseController {

    @Resource
    private UpmsResourceService upmsResourceService;
    @Resource
    private UpmsUserService upmsUserService;
    @Resource
    private AuthService authService;

    @InitBinder
    public void intiBinder(WebDataBinder binder) {
        binder.registerCustomEditor(UpmsResourcesType.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(UpmsResourcesType.valueOf(Integer.valueOf(text)));
            }
        });
        binder.registerCustomEditor(Status.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(Status.valueOf(Integer.valueOf(text)));
            }
        });
    }

    final String pagePath = "upms/resource/";


    /**
     * 获取所有菜单数据
     *
     * @return
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String toListPage(Model model) {
        model.addAttribute("resourceType", UpmsResourcesType.values());
        //系统列表
//        model.addAttribute("upmsSystem","");
        return pagePath + "resources-list";
    }


    /**
     * 获取所有菜单数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public List<UpmsResource> list() {
        return upmsResourceService.findAll();
    }



    /**
     * 获取所有菜单数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "listByUser", method = RequestMethod.POST)
    public List listByUser() {
        return authService.findResourcesByUser(getPrincipalId());
    }


    /**
     * 创建资源
     *
     * @param bean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public AjaxResult create(UpmsResource bean) {
        bean.setStatus(Status.normal);
        if (StringUtils.isEmpty(bean.getUrl())){
            bean.setUrl("/");
        }
        upmsResourceService.insert(bean);
        cleanUserResourceCache();
        return new AjaxResult(true,bean);
    }

    @RequestMapping(value = "create",method = RequestMethod.GET)
    public String toResourcePage(Model model){
        model.addAttribute("resourceType",UpmsResourcesType.values());
        return pagePath + "resource-create";
    }

    /**
     * 获取资源信息
     *
     * @param id 资源id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "get", method = RequestMethod.GET)
    public AjaxResult findById(Long id) {
        UpmsResource bean = upmsResourceService.get(id);
        return new AjaxResult(true, bean);
    }

    /**
     * 获取资源信息
     *
     * @param id 资源id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public AjaxResult delete(Long id) {
        upmsResourceService.delete(id);
        cleanUserResourceCache();
        return new AjaxResult(true,"操作成功");
    }

    /**
     * 编辑资源
     *
     * @param bean 资源信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    public AjaxResult edit(UpmsResource bean) {
        upmsResourceService.update(bean);

        //清除用户已有权限的缓存
        cleanUserResourceCache();
        return new AjaxResult(true,"操作成功");
    }

    @RequestMapping(value = "edit", method = RequestMethod.GET)
    public String toEditPage(Model model) {
        model.addAttribute("resourceType",UpmsResourcesType.values());
        return pagePath + "resource-edit";
    }

    @RequestMapping("clearMenuCacheByUsrId")
    @ResponseBody
    public AjaxResult clearMenuCacheByUserId(){
        cleanUserResourceCache();
        return new AjaxResult(true,"缓存已刷新");
    }

    /**
     * 检查资源名是否重复
     *
     * @param name
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "validName", method = RequestMethod.POST)
    public boolean validPhone(String name, Long id, Long pid) {
        return !upmsResourceService.validateName(name, id, pid);
    }

    /**
     * 编辑启用/禁用
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "editStatus", method = RequestMethod.POST)
    public AjaxResult editStatus(Status status, String id) {
        UpmsResource bean = upmsResourceService.get(Long.valueOf(id));
        bean.setStatus(status);
        int n = upmsResourceService.updateStatus(bean);

        //清除用户已有权限的缓存
        cleanUserResourceCache();
        if (n > 0){
            return new AjaxResult(true,"操作成功");
        }else{
            return new AjaxResult(false,"操作失败");
        }
    }

    /**
     * 移动节点
     */
    @ResponseBody
    @RequestMapping(value = "move",method = RequestMethod.POST)
    public AjaxResult moveUpmsResource(Long theMenuId,Long targetId){
        UpmsResource upmsResource = upmsResourceService.get(theMenuId);
        upmsResource.setPid(targetId);
        upmsResourceService.update(upmsResource);
        return new AjaxResult(true);
    }

    public static void main(String[] args) {
        Reflections reflections =new Reflections(new ConfigurationBuilder()
                .setUrls(ClasspathHelper.forPackage("com.inspinia.upms.server.controller.upms")));
        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(RequestMapping.class);
        Iterator<Class<?>> iterator = typesAnnotatedWith.iterator();
        while (iterator.hasNext()){
            Class<?> next = iterator.next();
            StringBuilder f = new StringBuilder();
            String[] value = next.getAnnotation(RequestMapping.class).value();
            String va = value[0];
            va = "/" + va + "/";
            Method[] m = next.getDeclaredMethods();
            for (int i = 0; i < m.length; i++) {
                if (Objects.nonNull( m[i].getAnnotation(RequestMapping.class))){
                    f.append(va + m[i].getAnnotation(RequestMapping.class).value()[0]+"\r\n");
                }
            }
            System.out.println(f.toString());
        }
    }
}
